package excel.server;

import excel.talkapi.fromclient.ClientRequest;
import excel.talkapi.fromclient.message.Build;
import excel.talkapi.fromserver.ServerResponse;
import excel.talkapi.fromserver.message.ServerStatus;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SocketDeamon implements Runnable {

    private final SocketCall socketCall;
    private final Socket socket;

    public SocketDeamon(SocketCall socketCall, Socket socket) {
        this.socketCall = socketCall;
        this.socket = socket;
    }

    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (socketCall.cancel()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ClientRequest clientRequest = (ClientRequest) ois.readObject();
                ois.close();
                if (clientRequest.getActions()[0].equals(Build.HELLO)) {
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    ServerResponse serverResponse = new ServerResponse();
                    serverResponse.setStatus(ServerStatus.BUSY);
                    oos.writeObject(serverResponse);
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
